import React, { useEffect, useRef, useState}  from "react";
import { withRouter } from "react-router-dom";
import commonConfig from 'static/js/commonConfig'
import { connect } from 'react-redux'
import {getWordInfo,getWordInfoPublish,wordStatusChange,setRemark,saveNewWord,getHistoryRemark,referenceListWord} from 'api/index'
import {notification,Modal,Tabs,Form,Select,Cascader,Spin,Alert} from 'antd'
import {checkDraftData,addHistoryRouter} from 'redux/action'
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm'
import  AudioUpload  from 'components/Upload/audio'
import  MoreUpload  from 'components/Upload/morePicture'
import LlxHead from "components/Operations/LlxHead"
const { SHOW_CHILD } = Cascader;
const { TabPane } = Tabs;
// 获取页面操作的权限  获取状态切换的权限 获取对应的值 
const {getPageJurisdiction,getStatusJurisdiction,statusValue} = commonConfig


// 查看更多弹框
const LookMores = (props) => {
  const {isModalVisible, setIsModalVisible} = props

  const id = window.location.href.slice(window.location.href.indexOf('id=')+3)

  useEffect(()=>{
    if(!isModalVisible) return
    getHistoryList()

    getUseList()
  },[isModalVisible])// eslint-disable-line react-hooks/exhaustive-deps

  
 //分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:10
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
const [dataSourceList,setDataSourceList] = useState([])
const [loading,setLoading] = useState(false)
const [total,setTotal] = useState(0)
//表头配置信息
const columns = [
      {title: '状态变更', dataIndex: 'statusNext', key: 'statusNext', align: 'center',render:(text,row)=>{
        return <div>
        {row.statusNow} → {row.statusNext}
        </div>
      }},
      {title: '留言', dataIndex: 'remark', key: 'remark', align: 'center'},
      {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center'},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center'}
]
 
const columnsList = [
      {title: '类型', dataIndex: 'type', key: 'type', align: 'center'},
      {title: '名称', dataIndex: 'name', key: 'name', align: 'center',render:(text,row)=>{
        return <div className="text-link" onClick={()=>goPage(row)}>
          {text}
        </div>
      }},
      {title: '当前状态', dataIndex: 'workStatus', key: 'workStatus', align: 'center'}
]
 
 const handleCancel = () => {
    setIsModalVisible(false);
 };

 const getHistoryList = async(value) => {
  setLoading(true)
  const res = await getHistoryRemark({ id: id, type:'WORD', currPage:value&&value.pageSize?value.current:pagination.current,
  pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize})
  setDataSource(res.result.records)
  setTotal(res.result.total)
  setLoading(false)
 }
 const getUseList = async () => {
  setLoading(true)
  const res = await referenceListWord(id)
  setDataSourceList(res.result)
  setLoading(false)
 }

 function callback(key) {
  console.log(key);
}

const goPage = (row) => {
  switch(row.type) {
    case '主题课':
      props.history.push('/view/plan/themeSubjectInfo?id=' + row.id)
      props.addRouter({
        menuName:'主题课详情',url:'plan/themeSubjectInfo?id=' + row.id 
      })
    break
    case '精读书':
      props.history.push('/view/book/intensiveBookInfo?id=' + row.id)
      props.addRouter({
        menuName:'精读书详情',url:'book/intensiveBookInfo?id=' + row.id 
      })
    break
    default:
      return
  }
}

return   <Modal wrapClassName='get-more' width={800} title="查看更多" visible={isModalVisible} footer={null} onCancel={handleCancel}>
         <Tabs defaultActiveKey="1" onChange={callback}>
          <TabPane tab="历史记录" key="1">
           {/* 表格 */}
             <LlxTable
              loading={loading} 
              pagination={pagination}
              setPagination={setPagination}
              selectedRowShow={false}
              height={640}
              total={total}
              getNewList={getHistoryList}
              columns={columns}
              dataSource={dataSource}/>
          </TabPane>
          <TabPane tab="引用列表" key="3">
           <LlxTable
              loading={loading} 
              selectedRowShow={false}
              height={640}
              paginationHide={true}
              getNewList={getUseList}
              columns={columnsList}
              dataSource={dataSourceList}/>
          </TabPane>
         </Tabs>
 </Modal>
}

const LookMore = withRouter(LookMores)


// 单词详情
const WordMain = (props) => {

  const {form,dictionaries,disabled,getWordInfoFn} = props
  const newWordItem = [
    {label: '单词名称',type:'input', name: 'wordName' , span: 12 ,rules:[
      {
        required: true,
        message: '请输入单词名称'
      },
    ]},
    {label: '英文释义',type:'input', name: 'englishExplain' , span: 12 },
    {label: '中文释义',type:'input', name: 'chineseExplain' , span: 12 },
    {label: '词性', name: 'pofId', span: 12 ,render:()=>{
      return  <Select
      allowClear
      disabled={disabled}
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择词性'}
      options={dictionaries.PartOfSpeech}
    >
    </Select>
    }},
    {label: '级别', name: 'levelId', span: 12 ,render:()=>{
      return   <Select
      disabled={disabled}
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'id',label:'dictValue'}}
      placeholder={'请选择级别'}
      options={dictionaries.Level}
    >
    </Select>
    }},
    {label: '标签', name: 'label', span: 12 ,render:()=>{
      return  <Cascader disabled={disabled}  maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} fieldNames={{value:'id',label:'labelName'}} options={dictionaries.Label} multiple placeholder="请选择标签" />
    }},
    {label: '音频', name: 'audioUrl', span: 13 ,rules:[
      {
        required: true,
        message: '请上传音频'
      },
    ],render:()=>{
      return  <AudioUpload updateInfo={getWordInfoFn}  disabled={disabled} audio={form.getFieldValue().audioUrl} setAudio={(value)=>form.setFieldsValue({...form.getFieldValue(),audioUrl:value})}></AudioUpload>
    }},
    {label: '写实图片', name: 'picRealistic', span: 12 ,render:()=>{
      return  <MoreUpload updateInfo={getWordInfoFn} disabled={disabled} pictureList={form.getFieldValue().picRealistic}  setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),picRealistic:value})}></MoreUpload>
    }},
    {label: '卡通图片', name: 'picCartoon', span: 12 ,render:()=>{
      return  <MoreUpload updateInfo={getWordInfoFn}  disabled={disabled} pictureList={form.getFieldValue().picCartoon}  setPhoto={(value)=>form.setFieldsValue({...form.getFieldValue(),picCartoon:value})}></MoreUpload>
    }},
    {label: '例句',type:'input', name: 'exampleSentence' , span: 12 },
    {label: '例句翻译',type:'input', name: 'exampleTranslate' , span: 12 },
    {label: '例句音频', name: 'exampleAudioUrl' , span: 13,render:()=>{
      return  <AudioUpload  disabled={disabled} audio={form.getFieldValue().exampleAudioUrl} setAudio={(value)=>form.setFieldsValue({...form.getFieldValue(),exampleAudioUrl:value})}></AudioUpload>
    }}
  ]

  return <div  className='info-main'>
    <LlxForm disabled={disabled} form={form} labelCol={5} formItem={newWordItem} />
  </div>
}
// 保存数据
const DataDialog  = (props) => {
const {isModalVisible, setIsModalVisible,form,changeStatus,UserSpecies,userName,disabled,QandPQ} = props
const value = statusValue(changeStatus,form.getFieldValue().wordStatus) //修改的状态
const manager = value==='Q'||value==='PQ'?QandPQ:UserSpecies
const [formItem] = Form.useForm();//单词详情
const item = ['N','PN','P'].includes(value)?[
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
]:[
    {label: '负责人', name: 'manager' , span: 24 ,rules:[
      {
        required: true,
        message: '请选择负责人'
      },
    ],render:()=>{
      return  <Select
      allowClear
      optionFilterProp="dictValue"
      showSearch
      fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择负责人'}
      options={manager}
    >
    </Select>
    }},
    {label: '备注内容',type:'textArea', name: 'remark' , span: 24 }
]
// 返回
 const handleCancel = () => {
    setIsModalVisible(false);
 };
//  确认修改
 const handleOk = () => {
  formItem.validateFields().then(async()=>{
  //  1更改状态
  await wordStatusChange({
    id: form.getFieldValue().id,
    wordStatus: value,
    qmanager: value==='Q'||value==='PQ'?formItem.getFieldValue().manager:'',
    rmanager: value==='R'||value==='PR'?formItem.getFieldValue().manager:'',
  })
   
  // 留言
  await setRemark({
    manager: formItem.getFieldValue().manager||'',
    dataId: form.getFieldValue().id,
    type: 'WORD',
    remark: formItem.getFieldValue().remark,
    statusNow: form.getFieldValue().wordStatus,
    statusNext: value
  })

  //  2修改数据
   if(!disabled){
    const picRealistic = form.getFieldValue().picRealistic?form.getFieldValue().picRealistic.map(i=>{
      return {pictureUrl:i.url||i.pictureUrl,pictureType:0}
    }):[]
    const picCartoon = form.getFieldValue().picCartoon?form.getFieldValue().picCartoon.map(i=>{
      return {pictureUrl:i.url||i.pictureUrl,pictureType:1}
    }):[]
    
    const wdWordPictureFlows = [...picRealistic,...picCartoon]

     const editValue = {
      id: form.getFieldValue().id,
      audioUrl: form.getFieldValue().audioUrl,
      chineseExplain: form.getFieldValue().chineseExplain,
      englishExplain: form.getFieldValue().englishExplain,
      levelId: form.getFieldValue().levelId || -99,
      pofId: form.getFieldValue().pofId || -99,
      wdWordExampleFlows:[
       {
        exampleAudioUrl: form.getFieldValue().exampleAudioUrl,
        exampleSentence: form.getFieldValue().exampleSentence,
        exampleTranslate: form.getFieldValue().exampleTranslate
       }
      ],
      wdWordPictureFlows,
      wordName: form.getFieldValue().wordName,
      labels:form.getFieldValue().label?.map(i=>{
        return {id:i[1]}
        })
     }
    await saveNewWord(editValue)

    notification.success({
      message: '保存成功',
      description: '操作人：' + userName,
      duration:1.5
    });
  
    props.getWordInfoFn()
    formItem.resetFields()
    setIsModalVisible(false);
   } else {
    props.getWordInfoFn()
    formItem.resetFields()
    setIsModalVisible(false);
   }
  })
 }

return   <>
<Modal onOk={handleOk}  width={600} title="保存数据" visible={isModalVisible}  onCancel={handleCancel}>
      <Alert className="edit-alert" message={'你确定要修改状态至' + value + '吗？'} type="success" />

     <LlxForm form={formItem} labelCol={3} formItem={item} />
 </Modal>
</>
}


function WordInfo(props) {

  const {examineStatus} = props
  const [isModalVisibleMore,setIsModalVisibleMore] = useState(false)
  const [isModalVisibleData,setIsModalVisibleData] = useState(false)
  const [disabled,setDisabled] = useState(false)
  const [loading,setLoading] = useState(true)
  const id = commonConfig.getUrlParams(props).id
  const [form] = Form.useForm();//单词详情
  const head = useRef()
  const [preservationJurisdiction,setPreservationJurisdiction] = useState({})
  // 1.获取数据
  useEffect(()=>{
    getWordInfoFn()
  }, [examineStatus])// eslint-disable-line react-hooks/exhaustive-deps


  // 2.查看更多
  const getMore = () => {
    setIsModalVisibleMore(true)
  }
  // 3.保存数据
  const preservationData = () => {
   const value = statusValue(head.current.current,form.getFieldValue().wordStatus)
   if(!getStatusJurisdiction(preservationJurisdiction[0],preservationJurisdiction[1],preservationJurisdiction[2],preservationJurisdiction[3],preservationJurisdiction[4],preservationJurisdiction[5]).includes(value)) {
    notification.error({
      message: '该数据你无法保存，请联系管理员',
      description: '操作人：' + props.userInfo.user.userName,
      duration:2
    });
    return
   }
  
  // 打开弹框 输入备注 修改状态 修改数据
  setIsModalVisibleData(true)


  }
  // 4.更新数据
  const getWordInfoFn = async () => {
    if(examineStatus){
      const res = await getWordInfoPublish(id)
      if(!res.result.id){
        notification.error({
          message: '该单词未发布过',
          duration:1.5
        });
        props.checkDraftDataBtn()
        setLoading(false)
        return
      }
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        examples:[
         {
          exampleAudioUrl: res.result.exampleAudioUrl,
          exampleSentence: res.result.exampleSentence,
          exampleTranslate: res.result.exampleTranslate
         }
        ],
        picRealistic:res.result.pictures.length?res.result.pictures.filter(i=>+i.pictureType===0):[],
        picCartoon:res.result.pictures.length?res.result.pictures.filter(i=>+i.pictureType===1):[],
        label:res.result.labels?.map(i=>{
          return [i.labelCategoryId,i.id]
          })
      })
      setDisabled(true)
  
      setLoading(false)
    } else {
      const res = await getWordInfo(id)
      form.setFieldsValue(res.result)
      form.setFieldsValue({
        wdWordExampleFlows:[
         {
          exampleAudioUrl: res.result.exampleAudioUrl,
          exampleSentence: res.result.exampleSentence,
          exampleTranslate: res.result.exampleTranslate
         }
        ],
        picRealistic:res.result.pictureFlows.length?res.result.pictureFlows.filter(i=>+i.pictureType===0):[],
        picCartoon:res.result.pictureFlows.length?res.result.pictureFlows.filter(i=>+i.pictureType===1):[],
        label:res.result.labels?.map(i=>{
          return [i.labelCategoryId,i.id]
          })
      })
      setDisabled(!getPageJurisdiction(res.result.wordStatus,res.result.createBy,props.userInfo.user.userName))

      setPreservationJurisdiction([res.result.wordStatus,res.result.createBy,res.result.rmanager,res.result.qmanager,props.userInfo.user.userName,props.userInfo.roles.map(i => i.id).includes(7)])
     
      setLoading(false)
    }
  }

  return <div className="app-content-info animate__animated animate__fadeIn">
  {
    !loading?(
      <>
      <LlxHead statusType={'wordStatus'} nameType={'wordName'}  examineStatus={examineStatus}  ref={head} preservationJurisdiction={preservationJurisdiction}  preservationData={preservationData} userName={props.userInfo.user.userName} role={props.userInfo.roles.map(i => i.id).includes(7)} form={form} getMore={getMore}></LlxHead>
       
       {/* 查看更多信息 */}
       <LookMore addRouter={props.addRouter}  preservationJurisdiction={preservationJurisdiction}  isModalVisible={isModalVisibleMore}  setIsModalVisible={setIsModalVisibleMore} ></LookMore>
       {/* 保存数据 */}
       <DataDialog getWordInfoFn={getWordInfoFn} disabled={disabled} form={form} QandPQ={props.dictionaries.QandPQ} UserSpecies={props.dictionaries.UserSpecies} userName={props.userInfo.user.userName} status={form} changeStatus={head.current?.current}   id={id} isModalVisible={isModalVisibleData} setIsModalVisible={setIsModalVisibleData} ></DataDialog>
       
       {/* 主要内容区域 */}
       {/* 1.草稿可编辑 */}
       <WordMain getWordInfoFn={getWordInfoFn} form={form} dictionaries={props.dictionaries} disabled={disabled}></WordMain>
      </>
    ):<Spin className="info-loading" tip="Loading..."></Spin>
  }
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkDraftDataBtn: () => dispatch(checkDraftData()),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
  }
}

export default connect((state)=>{
  return {examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(withRouter(WordInfo))